import axios from "axios";
import qs from "qs";
import {Message} from "element-ui";

const promiseArr = {},
  errorCode = [{code: 1, msg: "成功"}, {code: 0, msg: "逻辑错误"}, {code: -1, msg: "服务器错误"}, {code: -2, msg: "记录已存在"}, {code: -3, msg: "存在关联数据"}];

//成功提示返回
const responseUseSuccess = (response) => {
  if (response.data && response.data.code === 1) {
    return {data: response.data || {code: 1}, res: response};
  } else {
    let message = "请求成功";
    if (response.data) {
      if (typeof response.data === "object" || response.data.hasOwnProperty("code")) {
        const errorCodeItem = errorCode.find((element) => element.code === response.data.code);
        message = errorCodeItem ? errorCodeItem.msg : "";
        message = response.data ? response.data.msg : message;
        if (response.data.code && response.data.code !== 1 && response.data.msg) {
          Message.closeAll();
          Message({
            type: "error",
            message: "错误:" + response.data.msg,
            duration: 3000
          });
        }
        return {data: response.data || {code: 1, data: "", msg: message}, res: {...response, data: response.data || {code: 1, data: "", msg: message}}};
      } else {
        message = response.data.msg || message;
        return {data: {code: 1, data: response.data, msg: message}, res: {...response, data: response.data || {code: 1, data: response.data, msg: message}}};
      }
    }
    return {data: {code: 1, data: "", msg: message}, res: {...response, data: response.data || {code: 1, data: "", msg: message}}};
  }
};

// 错误提示返回
const responseUseError = function(error) {
  if (error && error.response) {
    switch (error.response.status) {
      case 400:
        error.message = "错误请求";
        break;
      case 401:
        error.message = "未授权，请重新登录";
        if (process.env.NODE_ENV === "development") {
          window._Vue._router.push("/login");
        }
        break;
      case 403:
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = "请求错误,未找到该资源";
        break;
      case 405:
        error.message = "请求方法未允许";
        break;
      case 408:
        error.message = "请求超时";
        break;
      case 500:
        error.message = "服务器端出错";
        break;
      case 501:
        error.message = "网络未实现";
        break;
      case 502:
        error.message = "网络错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网络超时";
        break;
      case 505:
        error.message = "http版本不支持该请求";
        break;
      default:
        error.message = `连接错误${error.response.status}`;
    }
  } else {
    error.message = "连接到服务器失败";
  }
  Message.closeAll();
  Message({
    type: "error",
    message: error.message,
    duration: 3000
  });
  return Promise.resolve({data: {code: -1, data: "", msg: error.message || "请求失败"}, res: {data: {code: -1, data: "", msg: error.message || "请求失败"}}});
};

let cancel;
const newAxios = (configParams) => {
  const newAxiosCreate = axios.create({
    baseURL: `http://${window.APP_SETTING.SERVER_HOST}:${window.APP_SETTING.SERVER_PORT}/`, // 请求基础地址
    timeout: 60000,
    headers: {"Content-Type": "application/x-www-form-urlencoded"}
  });

   /* 请求 */
   newAxiosCreate.defaults.transformRequest = (data = {}, headers) => {
    if (typeof data === "string") {
      return data;
    }
    // // 当前设备设置
    // if (window.SYSTEM_CONFIG.modules && (!data.module)) {
    //   data.module = window.SYSTEM_CONFIG.modules;
    // }
    const Authorization = sessionStorage.getItem(window.TOKEN_KEY) || localStorage.getItem(window.TOKEN_KEY) || null;
    if (Authorization) {
      if (!data.oauth) {
        data.oauth = Authorization;
      }
    }
    return qs.stringify(data);
  };

  // 请求拦截器
  newAxiosCreate.interceptors.request.use((config) => {
  // 发起请求时，取消掉当前正在进行的相同请求
    if (promiseArr[config.url]) {
      promiseArr[config.url]("操作取消");
      promiseArr[config.url] = cancel;
    } else {
      promiseArr[config.url] = cancel;
    }
    return config;
  }, (error) => Promise.reject(error));

  // 响应拦截器即异常处理
  if (configParams && configParams.hasOwnProperty("messageFlag")) {
    if (!configParams.messageFlag) {
      newAxiosCreate.interceptors.response.use(responseUseSuccess, (error) => {
        return Promise.resolve({data: {code: -1, data: "", msg: error.message || "请求失败"}, res: {data: {code: -1, data: "", msg: error.message || "请求失败"}}});
      });
    } else {
      newAxiosCreate.interceptors.response.use(responseUseSuccess, responseUseError);
    }
  } else {
    newAxiosCreate.interceptors.response.use(responseUseSuccess, responseUseError);
  }
  return newAxiosCreate;
};

const _axios = {
  _axios: newAxios(),
  request: (config) => newAxios().request(config),
  get: (url, config) => newAxios().get(url, config),
  delete: (url, config) => newAxios().delete(url, config),
  head: (url, config) => newAxios().head(url, config),
  options: (url, config) => newAxios().options(url, config),
  post: (url, data, config) => newAxios(config).post(url, data, config),
  put: (url, data, config) => newAxios().put(url, data, config),
  patch: (url, data, config) => newAxios().patch(url, data, config)
};

export {
  _axios
};
